package models

import (
	// "errors"
	"fmt"
	"strconv"

	"gitee.com/lzqysoft/goadmin/libs/encrypt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	// "reflect"
	// "strings"
	"time"
)

type Serv struct {
	Id            string    `orm:"column(id);pk"`
	ProdId        string    `orm:"column(prod_id)"`
	OrderId       string    `orm:"column(order_id)"`
	OrderName     string    `orm:"column(order_name);null"`
	CustId        string    `orm:"column(cust_id);null"`
	CustName      string    `orm:"column(cust_name);null"`
	Macid         string    `orm:"column(macid);null"`
	Name          string    `orm:"column(name)"`
	Model         string    `orm:"column(model)"`
	Spec          string    `orm:"column(spec)"`
	Price         float64   `orm:"column(price)"`
	DiscountPrice float64   `orm:"column(discount_price)"`
	Address       string    `orm:"column(address);null"`
	Contact       string    `orm:"column(contact);null"`
	Phone         string    `orm:"column(phone);null"`
	Account       string    `orm:"column(account);null"`
	Remark        string    `orm:"column(remark);null"`
	Status        int       `orm:"column(status)"`
	Isdelete      int       `orm:"column(isdelete)"`
	Ctime         time.Time `orm:"column(ctime);type(timestamp without time zone)"`
	Creater       string    `orm:"column(creater);null"`
	Utime         time.Time `orm:"column(utime);type(timestamp without time zone)"`
	Updater       string    `orm:"column(updater);null"`
}

func (t *Serv) TableName() string {
	return "yjk_serv"
}

func init() {
	orm.RegisterModel(new(Serv))
}

// AddServ insert a new Serv into database and returns
// last inserted Id on success.
func AddServ(m *Serv) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetServById retrieves Serv by Id. Returns error if
// Id doesn't exist
func GetServById(id string) (v *Serv, err error) {
	o := orm.NewOrm()
	v = &Serv{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllServ retrieves all Serv matches certain condition. Returns empty list if
// no records exist
func GetAllServ() (ml []orm.Params, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Serv))
	qs = qs.OrderBy("OrderId", "ProdId")
	_, err = qs.Limit(-1).Values(&ml)
	for _, v := range ml {
		order, _ := GetOrderById(v["OrderId"].(string))
		v["CustName"] = order.CustName
		v["OrderName"] = order.Name
	}
	return
}

// GetServs 服务端分页/查询/排序
func GetServs(sortby []string, order []string, offset int, limit int,
	searchKey string) (ml []Serv, total int64, err error) {
	o := orm.NewOrm()

	sql := "select * from yjk_serv "
	var servs []Serv
	if searchKey != "" {
		sql = sql + " where record_to_text(yjk_serv) ~ '" + searchKey + "' "
	}
	total, err = o.Raw(sql).QueryRows(&servs)
	if err != nil {
		return nil, 0, err
	}
	// order by:
	var sortFields string
	if len(sortby) != 0 && len(sortby) == len(order) {
		// 1) for each sort field, there is an associated order
		for i, v := range sortby {
			if i > 0 {
				sortFields = sortFields + ","
			}
			orderby := " " + v + " " + order[i] + " "
			sortFields = sortFields + orderby
		}
		sql = sql + " order by " + sortFields
	}
	if limit > 0 {
		sql = sql + " limit " + strconv.Itoa(limit) + " offset " + strconv.Itoa(offset)
	}

	beego.Debug(sql)
	_, err = o.Raw(sql).QueryRows(&ml)
	if err != nil {
		return nil, 0, err
	}
	return
}

// UpdateServ updates Serv by Id and returns error if
// the record to be updated doesn't exist
func UpdateServById(m *Serv) (err error) {
	o := orm.NewOrm()
	v := Serv{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteServ deletes Serv by Id and returns error if
// the record to be deleted doesn't exist
func DeleteServ(id string) (err error) {
	o := orm.NewOrm()
	v := Serv{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Serv{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// AddServByOrder 添加服务实例根据订单
func AddServByOrder(id string) (err error) {
	sales, err := GetSalesByOrder(id)
	if err != nil {
		beego.Error(err)
		return
	}
	order, _ := GetOrderById(id)
	cust, _ := GetCustById(order.CustId)
	o := orm.NewOrm()
	for _, s := range sales {
		var v Serv
		prod, _ := GetProdById(s.ProdId)
		//产品类型为服务则不插入服务实例
		if ProdTypeIs(prod.Prodtype, "2") {
			continue
		}
		for i := 0; i < s.Count; i++ {
			v.Account = s.Account
			v.Address = cust.Address
			v.Contact = cust.Contact
			v.DiscountPrice = s.DiscountPrice
			v.Model = s.Model
			v.Name = s.Name
			v.OrderId = id
			v.CustId = cust.Id
			v.OrderName = order.Name
			v.CustName = cust.Name
			v.Phone = cust.Phone
			v.Price = s.Price
			v.ProdId = s.ProdId
			v.Spec = s.Spec
			v.Creater = s.Creater
			v.Ctime = time.Now()
			v.Updater = s.Updater
			v.Utime = time.Now()
			v.Id = encrypt.GetGuid()
			v.Macid = "1"
			_, err = o.Insert(&v)
		}
	}
	return
}
